package com.xiang.springboot.demo.spi.config;

import com.xiang.springboot.demo.spi.service.ISpi;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

@Component
public class SpiFactoryBean implements ApplicationContextAware {

    private List<ISpi> list;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, ? extends ISpi> map = applicationContext.getBeansOfType(ISpi.class);
        list = new ArrayList<>(map.values());
        list.sort(Comparator.comparingInt(ISpi::order));
    }

    public <T extends ISpi> T getBean(Class clazz) {
        for (ISpi spi:list){
            if(clazz.equals(spi.businessFor())){
                return (T) spi;
            }
        }
        return null;
    }
}
